import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Card, Space, Button, Tooltip, Row, Col, message } from 'antd';
import {
  SaveOutlined,
  UndoOutlined,
  RedoOutlined,
  FormatPainterOutlined,
  EyeOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import Editor, { Monaco } from '@monaco-editor/react';
import type { editor } from 'monaco-editor';
import { PromptTemplate, PromptVariable } from '@/types/prompt';
import { extractVariables, findUndefinedVariables } from '@/utils/variable-parser';
import { inputSanitizer } from '@/utils/input-sanitizer';
import './style.css';

interface PromptEditorProps {
  value?: string;
  onChange?: (value: string) => void;
  variables?: PromptVariable[];
  onVariablesDetected?: (variables: string[]) => void;
  template?: PromptTemplate;
  onSave?: (content: string) => void;
  readOnly?: boolean;
  height?: string;
  showPreview?: boolean;
  onPreviewToggle?: (show: boolean) => void;
}

const PromptEditor: React.FC<PromptEditorProps> = ({
  value = '',
  onChange,
  variables = [],
  onVariablesDetected,
  template,
  onSave,
  readOnly = false,
  height = '400px',
  showPreview = false,
  onPreviewToggle
}) => {
  const [content, setContent] = useState(value);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [detectedVars, setDetectedVars] = useState<string[]>([]);
  const [undefinedVars, setUndefinedVars] = useState<string[]>([]);
  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
  const monacoRef = useRef<Monaco | null>(null);

  // 初始化内容
  useEffect(() => {
    setContent(value);
  }, [value]);

  // 检测变量
  useEffect(() => {
    const vars = extractVariables(content);
    setDetectedVars(vars);
    
    const undefined = findUndefinedVariables(content, variables);
    setUndefinedVars(undefined);
    
    if (onVariablesDetected) {
      onVariablesDetected(vars);
    }
  }, [content, variables, onVariablesDetected]);

  // Monaco Editor 初始化
  const handleEditorWillMount = (monaco: Monaco) => {
    monacoRef.current = monaco;
    
    // 注册自定义语言
    monaco.languages.register({ id: 'prompt' });
    
    // 定义语法高亮规则
    monaco.languages.setMonarchTokensProvider('prompt', {
      tokenizer: {
        root: [
          // 变量高亮
          [/\{[^}]+\}/, 'variable'],
          // Markdown 标题
          [/^#{1,6}\s.*$/, 'heading'],
          // 强调文本
          [/\*\*.*?\*\*/, 'bold'],
          [/\*.*?\*/, 'italic'],
          // 代码块
          [/`[^`]+`/, 'code'],
          // 列表
          [/^[\s]*[-*+]\s/, 'list'],
          [/^[\s]*\d+\.\s/, 'list'],
          // 引用
          [/^>\s.*$/, 'quote'],
        ]
      }
    });

    // 定义主题
    monaco.editor.defineTheme('prompt-theme', {
      base: 'vs',
      inherit: true,
      rules: [
        { token: 'variable', foreground: 'FF6B6B', fontStyle: 'bold' },
        { token: 'heading', foreground: '4ECDC4', fontStyle: 'bold' },
        { token: 'bold', fontStyle: 'bold' },
        { token: 'italic', fontStyle: 'italic' },
        { token: 'code', foreground: '95E77E', background: 'F0F0F0' },
        { token: 'list', foreground: '556270' },
        { token: 'quote', foreground: '999999', fontStyle: 'italic' },
      ],
      colors: {}
    });
  };

  // Editor 挂载后的处理
  const handleEditorDidMount = (editor: editor.IStandaloneCodeEditor, monaco: Monaco) => {
    editorRef.current = editor;
    
    // 设置主题
    monaco.editor.setTheme('prompt-theme');
    
    // 注册快捷键
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
      handleSave();
    });
    
    // 自动补全
    monaco.languages.registerCompletionItemProvider('prompt', {
      provideCompletionItems: (model, position) => {
        const suggestions: any[] = [];
        
        // 变量自动补全
        variables.forEach(variable => {
          suggestions.push({
            label: `{${variable.name}}`,
            kind: monaco.languages.CompletionItemKind.Variable,
            insertText: `{${variable.name}}`,
            detail: variable.description || variable.name,
            documentation: `类型: ${variable.type}${variable.required ? ' (必需)' : ' (可选)'}`
          });
        });
        
        // 常用模板片段
        suggestions.push({
          label: 'role',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: '你是${1:角色}，擅长${2:技能}。',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          documentation: '角色定义模板'
        });
        
        suggestions.push({
          label: 'task',
          kind: monaco.languages.CompletionItemKind.Snippet,
          insertText: '请${1:完成任务}，要求：\n1. ${2:要求1}\n2. ${3:要求2}',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          documentation: '任务定义模板'
        });
        
        return { suggestions };
      }
    });
  };

  // 内容变化处理
  const handleEditorChange = (value: string | undefined) => {
    const newContent = value || '';
    
    // 安全验证
    const validation = inputSanitizer.validatePromptContent(newContent);
    if (!validation.isValid) {
      validation.issues.forEach(issue => {
        message.warning(`安全警告: ${issue}`);
      });
      // 清理内容
      const sanitized = inputSanitizer.sanitizeString(newContent);
      setContent(sanitized);
      if (onChange) {
        onChange(sanitized);
      }
    } else {
      setContent(newContent);
      if (onChange) {
        onChange(newContent);
      }
    }
    
    setHasChanges(newContent !== value);
  };

  // 保存
  const handleSave = useCallback(() => {
    if (onSave) {
      // 最终安全检查
      const validation = inputSanitizer.validatePromptContent(content);
      if (!validation.isValid) {
        message.error(`保存失败: ${validation.issues.join(', ')}`);
        return;
      }
      
      const sanitizedContent = inputSanitizer.sanitizeString(content);
      onSave(sanitizedContent);
      setHasChanges(false);
      message.success('保存成功');
    }
  }, [content, onSave]);

  // 撤销
  const handleUndo = () => {
    editorRef.current?.trigger('keyboard', 'undo', null);
  };

  // 重做
  const handleRedo = () => {
    editorRef.current?.trigger('keyboard', 'redo', null);
  };

  // 格式化
  const handleFormat = () => {
    editorRef.current?.getAction('editor.action.formatDocument')?.run();
    message.success('格式化完成');
  };

  // 预览切换
  const handlePreviewToggle = () => {
    const newShowPreview = !showPreview;
    if (onPreviewToggle) {
      onPreviewToggle(newShowPreview);
    }
  };

  // 全屏切换
  const handleFullscreenToggle = () => {
    setIsFullscreen(!isFullscreen);
  };

  return (
    <div className={`prompt-editor-container ${isFullscreen ? 'fullscreen' : ''}`}>
      <Card
        className="prompt-editor-card"
        title={
          <Space>
            <span>提示词编辑器</span>
            {template && (
              <Tooltip title={template.description}>
                <span className="template-name">- {template.name}</span>
              </Tooltip>
            )}
            {hasChanges && <span className="unsaved-indicator">●</span>}
          </Space>
        }
        extra={
          <Space>
            {!readOnly && (
              <>
                <Tooltip title="保存 (Ctrl+S)">
                  <Button
                    icon={<SaveOutlined />}
                    onClick={handleSave}
                    type={hasChanges ? 'primary' : 'default'}
                  >
                    保存
                  </Button>
                </Tooltip>
                <Tooltip title="撤销">
                  <Button icon={<UndoOutlined />} onClick={handleUndo} />
                </Tooltip>
                <Tooltip title="重做">
                  <Button icon={<RedoOutlined />} onClick={handleRedo} />
                </Tooltip>
                <Tooltip title="格式化">
                  <Button icon={<FormatPainterOutlined />} onClick={handleFormat} />
                </Tooltip>
              </>
            )}
            <Tooltip title="预览">
              <Button
                icon={<EyeOutlined />}
                onClick={handlePreviewToggle}
                type={showPreview ? 'primary' : 'default'}
              />
            </Tooltip>
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
              <Button
                icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                onClick={handleFullscreenToggle}
              />
            </Tooltip>
          </Space>
        }
      >
        <div className="editor-info-bar">
          <Row gutter={16}>
            <Col span={12}>
              <Space>
                <span>检测到的变量：</span>
                {detectedVars.map(v => (
                  <Tooltip key={v} title="点击复制">
                    <span
                      className="detected-variable"
                      onClick={() => {
                        navigator.clipboard.writeText(`{${v}}`);
                        message.success('已复制到剪贴板');
                      }}
                    >
                      {`{${v}}`}
                    </span>
                  </Tooltip>
                ))}
              </Space>
            </Col>
            <Col span={12}>
              {undefinedVars.length > 0 && (
                <Space>
                  <InfoCircleOutlined className="warning-icon" />
                  <span className="warning-text">
                    未定义的变量：{undefinedVars.map(v => `{${v}}`).join(', ')}
                  </span>
                </Space>
              )}
            </Col>
          </Row>
        </div>
        
        <div className="editor-wrapper" style={{ height: isFullscreen ? 'calc(100vh - 200px)' : height }}>
          <Editor
            height="100%"
            defaultLanguage="prompt"
            language="prompt"
            value={content}
            onChange={handleEditorChange}
            beforeMount={handleEditorWillMount}
            onMount={handleEditorDidMount}
            options={{
              readOnly,
              minimap: { enabled: false },
              fontSize: 14,
              wordWrap: 'on',
              lineNumbers: 'on',
              renderWhitespace: 'selection',
              scrollBeyondLastLine: false,
              automaticLayout: true,
              suggestOnTriggerCharacters: true,
              quickSuggestions: {
                other: true,
                comments: true,
                strings: true
              },
              parameterHints: {
                enabled: true
              },
              bracketPairColorization: {
                enabled: true
              }
            }}
          />
        </div>
        
        <div className="editor-status-bar">
          <Row>
            <Col span={12}>
              <Space>
                <span>字符数：{content.length}</span>
                <span>行数：{content.split('\n').length}</span>
              </Space>
            </Col>
            <Col span={12} style={{ textAlign: 'right' }}>
              <Space>
                <span>语言：Prompt</span>
                <span>编码：UTF-8</span>
              </Space>
            </Col>
          </Row>
        </div>
      </Card>
    </div>
  );
};

export default PromptEditor;